package com.peanut.controller;

import cn.hutool.crypto.digest.MD5;
import com.mvc.annotation.*;
import com.peanut.constants.Constants;
import com.peanut.constants.Status;
import com.peanut.entity.AdminUser;
import com.peanut.entity.JsonResult;
import com.peanut.entity.Page;
import com.peanut.entity.Role;
import com.peanut.entity.dto.PermissionVO;
import com.peanut.service.RoleService;
import com.spring.annotation.Autowired;
import com.spring.annotation.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Controller
public class RoleController {
	@Autowired
	private RoleService service;
	
	/**
	 * 查询所有角色
	 */
	@RequestMapping(value = "/role/query.do")
	@ResponseBody
	public JsonResult queryAllRole() {
		List<Role> roles = service.listAll();
		JsonResult json = JsonResult.success(roles);
		return json;
	}
	
	
	/**
	 * 添加角色
	 */
	@RequestMapping(value = "/role/add.do")
	@ResponseBody
	public JsonResult addAdminUser(@RequestBody @Valid Role role) {
		if(service.save(role)){
			return JsonResult.success();
		}else {
			return JsonResult.fail();
		}
	}
	
	/**
	 * 修改角色名字
	 */
	@RequestMapping(value = "/role/update.do")
	@ResponseBody
	public JsonResult updateAdminUser(@RequestBody @Valid Role role) {
		if (service.update(role)) {
			return JsonResult.success();
		}
		return JsonResult.fail();
	}
	
	
	/**
	 * 删除角色,检查是否存在 关联用户 和 关联权限？
	 */
	@RequestMapping(value = "/role/delete.do")
	@ResponseBody
	public JsonResult deleteRole(@RequestParam(required = true) Integer id) {
		Role role = service.getById(id);
		if(role.getId().equals(1)){
			return JsonResult.status(Status.CANNOT_DELETE_INNER_ADMIN);
		}
		return service.deleteRole(id);
	}
	
	
	/*
	 * 下面是角色权限相关
	 */
	@RequestMapping(value = "/permission/query.do")
	@ResponseBody
	public JsonResult queryPermissionByRoleId(@RequestParam(required = true) Integer roleId) {
		PermissionVO permissionVO = service.queryPermission(roleId);
		return JsonResult.success(permissionVO);
	}
	

	@RequestMapping(value = "/permission/update.do")
	@ResponseBody
	public JsonResult updatePermission(@RequestBody PermissionVO permissionVO,HttpServletRequest request) {
		Map<Integer, List<String>> permissionsList = (Map<Integer, List<String>>) request.getServletContext().getAttribute(Constants.PERMISSIONS);
		
		boolean b = service.updatePermission(permissionVO,permissionsList);
		if(b){
			return JsonResult.success();
		}
		return JsonResult.fail();
	}
	
	
	@RequestMapping(value = "/permission/queryAllInterface.do")
	@ResponseBody
	public JsonResult queryAllInterface() {
		return JsonResult.success(service.queryAllInterface());
	}
}
